#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include <cstdlib>
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace std;
const static int defaultsock = -1;
const static int backlog = 16;

class TcpServer
{
public:
    TcpServer(uint16_t port, int sock = defaultsock):_port(port),_listensock(sock),_isrunning(false)
    {}

    void InitServer()
    {
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if(_listensock < 0)
        {
            LOG(FATAL, "socket error");
            exit(1);
        }
        LOG(INFO, "socket create success, sockfd: %d", _listensock);

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(_listensock, (struct sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            LOG(FATAL, "bind error");
            exit(2);
        }
        LOG(INFO, "bind create success, sockfd: %d", _listensock);

        n = listen(_listensock, backlog);
        if(n < 0)
        {
            LOG(FATAL, "listen error");
            exit(3);
        }
        LOG(INFO, "listen create success, sockfd: %d", _listensock);
    }

    void Server(int sockfd, InetAddr client)
    {
        LOG(DEBUG, "get a new link sockfd: %d, %s:%d", sockfd, client.Ip().c_str(), to_string(client.Port()));
        string clientaddr = "[" + client.Ip() + ":" + to_string(client.Port()) + "]# ";
        while(true)
        {
            char inbuffer[1024];
            ssize_t n = read(sockfd, inbuffer, sizeof(inbuffer));
            if(n > 0)
            {
                inbuffer[n] = 0;
                cout << clientaddr << inbuffer << endl;

                string echo_string = "[server echo]# ";
                echo_string += inbuffer;

                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if(n == 0)
            {
                LOG(WARNING, "%s quit", clientaddr.c_str());
                break;
            }
            else 
            {
                LOG(ERROR, "read error");
                break;
            }
        }
        close(sockfd);
    }

    void Loop()
    {
        _isrunning = true;
        while(_isrunning)
        {   
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensock, (struct sockaddr*)&peer, &len);
            if(sockfd < 0)
            {
                LOG(WARNING, "listen error");
                continue;
            }
            Server(sockfd, InetAddr(peer));
        }
    }

    ~TcpServer()
    {
        if(_listensock > defaultsock)
            close(_listensock);
    }

private:    
    uint16_t _port;
    int _listensock;
    bool _isrunning;
};